package com.xcc.server;

import com.xcc.server.decoder.MessageDecoder;
import com.xcc.server.domains.vo.Message;
import com.xcc.server.encoder.MessageEncoder;
import com.xcc.server.hadler.ServerHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.util.CharsetUtil;

import java.io.IOException;

/**
 * @author Carman
 * @date 2021/2/4 17:35
 * @desc 客户端
 */
public class Client {

    private NioEventLoopGroup nioEventLoopGroup;
    private Bootstrap bootstrap;
    private ChannelFuture future;


    public Client() throws InterruptedException, IOException {
        nioEventLoopGroup = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(nioEventLoopGroup).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
//                        .addLast(new DelimiterBasedFrameDecoder(4096, Delimiters.lineDelimiter()))
                                .addLast(new LineBasedFrameDecoder(1024))
                                .addLast(new MessageDecoder(CharsetUtil.UTF_8))   // 解码
                                .addLast(new MessageEncoder(CharsetUtil.UTF_8))  // 编码
//                                    .addLast(new LoggingHandler(LogLevel.INFO))  // 日志
                                .addLast(new ServerHandler());
                    }
                });

    }

    public void start(String ip, int port) {
        try {
            future = bootstrap.connect(ip, port).sync();
            // 消息发送示例代码
//            Channel channel = future.channel();
//            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//            while (true) {
//                String message = br.readLine();
//                channel.writeAndFlush(message);
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void close() {
        if (null == future) {
            return;
        }
        future.channel().close();
    }

    // 发送消息
    public ChannelFuture sendMesage(Message<?> message) {
        if (null == future) {
            throw new RuntimeException("未连接不允许发送信息");
        }
        return future.channel().writeAndFlush(message);
    }
}
